const {
  createAddress,
  findAllAddress,
  updateAddress,
  removeAddress,
  setDefaultAddress,
} = require("../service/addr.service");
const {
  addAddressFail,
  addAddressError,
  findAllAddressFail,
  findAllAddressError,
  updateAddressFail,
  updateAddressError,
  removeAddressFail,
  removeAddressError,
  setDefaultAddressFail,
  setDefaultAddressError,
} = require("../constant/error.type");

class AddrController {
  async create(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const { consignee, phone, address } = ctx.request.body;
      const res = await createAddress({ user_id, consignee, phone, address });
      if (res) {
        ctx.body = {
          code: 0,
          message: "创建地址成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", addAddressFail, ctx);
      }
    } catch (error) {
      console.error("创建地址出错", error);
      return ctx.app.emit("error", addAddressError, ctx);
    }
  }
  async findAll(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const res = await findAllAddress(user_id);
      if (res) {
        ctx.body = {
          code: 0,
          message: "获取地址成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", findAllAddressFail, ctx);
      }
    } catch (error) {
      console.error("获取地址出错", error);
      return ctx.app.emit("error", findAllAddressError, ctx);
    }
  }
  async update(ctx) {
    try {
      const id = ctx.request.params.id;
      const { consignee, phone, address } = ctx.request.body;
      const res = await updateAddress(id, { consignee, phone, address });
      if (res) {
        ctx.body = {
          code: 0,
          message: "更新地址成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", updateAddressFail, ctx);
      }
    } catch (error) {
      console.error("更新地址出错", error);
      return ctx.app.emit("error", updateAddressError, ctx);
    }
  }
  async remove(ctx) {
    try {
      const id = ctx.request.params.id;
      const res = await removeAddress(id);
      if (res) {
        ctx.body = {
          code: 0,
          message: "删除地址成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", removeAddressFail, ctx);
      }
    } catch (error) {
      console.error("删除地址出错", error);
      return ctx.app.emit("error", removeAddressError, ctx);
    }
  }
  async setDefault(ctx) {
    try {
      const user_id = ctx.state.user.id;
      const id = ctx.request.params.id;
      const res = await setDefaultAddress(user_id, id);
      if (res) {
        ctx.body = {
          code: 0,
          message: "设置默认地址成功",
          result: res,
        };
      } else {
        return ctx.app.emit("error", setDefaultAddressFail, ctx);
      }
    } catch (error) {
      console.error("设置默认地址出错", error);
      return ctx.app.emit("error", setDefaultAddressError, ctx);
    }
  }
}

module.exports = new AddrController();
